<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>go基础整理 | 指尖改变世界</title><meta name="keywords" content="go基础整理"><meta name="author" content="沙屿沫"><meta name="copyright" content="沙屿沫"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="go基础整理">
<meta property="og:type" content="article">
<meta property="og:title" content="go基础整理">
<meta property="og:url" content="http://blog.shayvmo.cn/2022/01/16/go-basic/index.html">
<meta property="og:site_name" content="指尖改变世界">
<meta property="og:description" content="go基础整理">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.shayvmo.cn/images/code.jpg">
<meta property="article:published_time" content="2022-01-16T13:41:08.000Z">
<meta property="article:modified_time" content="2022-04-25T02:24:04.532Z">
<meta property="article:author" content="沙屿沫">
<meta property="article:tag" content="Go">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.shayvmo.cn/images/code.jpg"><link rel="shortcut icon" href="/images/avatar.jpg"><link rel="canonical" href="http://blog.shayvmo.cn/2022/01/16/go-basic/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?5e4d1e8fcc524b4e732ea58fa9fa15f0";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'go基础整理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-25 10:24:04'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/images/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">74</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">42</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/images/code.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">指尖改变世界</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">go基础整理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-01-16T13:41:08.000Z" title="发表于 2022-01-16 21:41:08">2022-01-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-25T02:24:04.532Z" title="更新于 2022-04-25 10:24:04">2022-04-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Go/">Go</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="go基础整理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><strong>本章节内容来自《菜鸟教程》，并经过整理后记录</strong></p>
<hr>
<h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><ul>
<li>布尔型</li>
<li>数字类型</li>
<li>字符串类型</li>
<li>派生类型<ul>
<li>指针类型</li>
<li>数组类型</li>
<li>结构化类型</li>
<li>Channel类型</li>
<li>函数类型</li>
<li>切片类型</li>
<li>接口类型</li>
<li>Map类型</li>
</ul>
</li>
</ul>
<hr>
<h3 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h3><ul>
<li>全局变量允许声明而不使用，但是局部变量声明则必须使用</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var identifier type</span><br><span class="line"></span><br><span class="line"># 例如</span><br><span class="line"></span><br><span class="line">var a int</span><br><span class="line">a = 1</span><br><span class="line"></span><br><span class="line">b := 2</span><br><span class="line"></span><br><span class="line">fmt.Println(a, b)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> (</span><br><span class="line">    x <span class="keyword">int</span></span><br><span class="line">    y <span class="keyword">bool</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> a, b <span class="keyword">int</span></span><br><span class="line">    c := <span class="string">&quot;shayvmo&quot;</span></span><br><span class="line">    fmt.Println(a, b, c, x, y)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="number">0</span> <span class="number">0</span> shayvmo <span class="number">0</span> <span class="literal">false</span></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="常量"><a href="#常量" class="headerlink" title="常量"></a>常量</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">const identifier [type] = value</span><br><span class="line"></span><br><span class="line">// 显式类型定义</span><br><span class="line">const a string = &quot;abc&quot;</span><br><span class="line"></span><br><span class="line">// 隐式类型定义</span><br><span class="line">const b = 4</span><br></pre></td></tr></table></figure>

<h4 id="iota"><a href="#iota" class="headerlink" title="iota"></a>iota</h4><blockquote>
<p>iota 在 const关键字出现时将被重置为 0(const 内部的第一行之前)，const 中每新增一行常量声明将使 iota 计数一次(iota 可理解为 const 语句块中的行索引)</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">    const (</span><br><span class="line">        a = iota</span><br><span class="line">        b</span><br><span class="line">        c</span><br><span class="line">        d = &quot;ha&quot;</span><br><span class="line">        e</span><br><span class="line">        f = 100</span><br><span class="line">        g</span><br><span class="line">        h = iota</span><br><span class="line">        i</span><br><span class="line">    )</span><br><span class="line">    fmt.Println(a, b, c, d, e, f, g, h, i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="位运算符"><a href="#位运算符" class="headerlink" title="位运算符"></a>位运算符</h3><ul>
<li><code>&amp;</code> 按位与</li>
<li><code>|</code> 按位或</li>
<li><code>^</code> 按位异或</li>
<li><code>&gt;&gt;</code> 右移 右移n位，相当于是除以2的n次方</li>
<li><code>&lt;&lt;</code> 左移 左移n位，相当于是乘以2的n次方</li>
</ul>
<hr>
<h3 id="条件语句"><a href="#条件语句" class="headerlink" title="条件语句"></a>条件语句</h3><p>switch: 默认每个case都有break操作，只要匹配到了，则不再匹配。如果需要执行后面的case，可以使用 fallthrough</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">switch a &#123;</span><br><span class="line">	case 1:</span><br><span class="line">		fmt.Println(&quot;a匹配上了1&quot;)</span><br><span class="line">		fallthrough</span><br><span class="line">	case 2:</span><br><span class="line">		fmt.Printf(&quot;a虽然匹配上了1，加上fallthrough也能执行下面的case&quot;)</span><br><span class="line">	default:</span><br><span class="line">		fmt.Println(&quot;default&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="循环语句"><a href="#循环语句" class="headerlink" title="循环语句"></a>循环语句</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">for [init]; condition; [post] &#123;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 例如</span><br><span class="line"></span><br><span class="line">for i := 0; i &lt; 10; i++ &#123;&#125;</span><br><span class="line"></span><br><span class="line">i := 1;</span><br><span class="line"></span><br><span class="line">for ; i &lt; 10; &#123;</span><br><span class="line">    i += i * 2</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">func function_name([params_list]) [return_type] &#123;</span><br><span class="line">    函数体</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="函数的参数"><a href="#函数的参数" class="headerlink" title="函数的参数"></a>函数的参数</h4><ul>
<li>值传递（默认）</li>
<li>引用传递</li>
</ul>
<h4 id="函数用法"><a href="#函数用法" class="headerlink" title="函数用法"></a>函数用法</h4><ul>
<li>函数作为另一个函数的实参</li>
<li>闭包</li>
<li>方法</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;fmt&quot;</span><br><span class="line">	&quot;strconv&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">// 函数类型变量</span><br><span class="line">type callBack func(int)</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	callBackTest(2, func(i int) &#123;</span><br><span class="line">		fmt.Println(&quot;回调的函数：&quot; + strconv.Itoa(i))</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func callBackTest(x int, f callBack) &#123;</span><br><span class="line">	f(x)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="变量作用域"><a href="#变量作用域" class="headerlink" title="变量作用域"></a>变量作用域</h3><ul>
<li>全局</li>
<li>局部</li>
<li>形式参数</li>
</ul>
<hr>
<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"># 声明数组</span><br><span class="line">var varible_name [size] varible_type</span><br><span class="line"></span><br><span class="line"># 长度为10的整型数组</span><br><span class="line">var a [10] int </span><br></pre></td></tr></table></figure>

<p>初始化数组</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"># 初始化</span><br><span class="line">var a = [...]int&#123;1,2,3,4,5&#125;</span><br><span class="line"></span><br><span class="line"># 或</span><br><span class="line">a := [...]int&#123;2,24,42,3&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="指针"><a href="#指针" class="headerlink" title="指针"></a>指针</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"># 声明格式</span><br><span class="line">var var_name *var_type</span><br><span class="line"></span><br><span class="line"># 执行int类型的指针 a1</span><br><span class="line">var a1 *int</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="结构体"><a href="#结构体" class="headerlink" title="结构体"></a>结构体</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">type struct_varible_type struct &#123;</span><br><span class="line">    member definition</span><br><span class="line">    ...</span><br><span class="line">    member definition</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 初始化</span><br><span class="line">variable_name := structure_variable_type &#123;value1, value2...valuen&#125;</span><br><span class="line"># 或</span><br><span class="line">variable_name := structure_variable_type &#123; key1: value1, key2: value2..., keyn: valuen&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>例如</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">type Book struct &#123;</span><br><span class="line">    title string</span><br><span class="line">    author string</span><br><span class="line">    book_id int</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">    var book1 Book</span><br><span class="line">    </span><br><span class="line">	book1.title = &quot;何以笙箫默&quot;</span><br><span class="line">	book1.author = &quot;顾漫&quot;</span><br><span class="line">	book1.bookId = 123</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="结构体指针"><a href="#结构体指针" class="headerlink" title="结构体指针"></a>结构体指针</h4><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var struct_pointer *Book</span><br><span class="line"></span><br><span class="line">var book1Pointer *Book</span><br><span class="line">book1Pointer = &amp;book1</span><br><span class="line">fmt.Printf(&quot;%p\n&quot;, book1Pointer)</span><br><span class="line"></span><br><span class="line"># 何以笙箫默</span><br><span class="line">book1Pointer.title</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="切片"><a href="#切片" class="headerlink" title="切片"></a>切片</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var identifier []type</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">    arr := [...]int&#123;1,2,3&#125;</span><br><span class="line"></span><br><span class="line">	var slice = make([]int, 5)</span><br><span class="line">	slice1 := make([]int, 5)</span><br><span class="line">	slice2 := []int &#123;0,1,2,3,4,5,6,7&#125;</span><br><span class="line">	slice3 := arr[1:]</span><br><span class="line">	</span><br><span class="line">	fmt.Println(slice, slice1, slice2, slice3)</span><br><span class="line">	</span><br><span class="line">	slice2 = append(slice2, 8)</span><br><span class="line">	slice4 := make([]int, len(slice2), cap(slice2) * 2)</span><br><span class="line">	copy(slice4, slice2)</span><br><span class="line">	printSlice(slice2)</span><br><span class="line">	printSlice(slice4)</span><br><span class="line">	</span><br><span class="line">	fmt.Printf(&quot;slice2[1:4] = %v&quot;, slice2[1:4])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func printSlice(x []int) &#123;</span><br><span class="line">	fmt.Printf(&quot;len=%d cap=%d value=%v\n&quot;, len(x), cap(x), x)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="append-和-copy"><a href="#append-和-copy" class="headerlink" title="append 和 copy"></a>append 和 copy</h4><p>append 向切片添加元素</p>
<ul>
<li>当 append 一个满的切片时，最大长度会自动扩容，并且扩容到当前cap的2倍</li>
</ul>
<p>copy 复制原切片到新的切片（如果需要扩容时，需要先创建一个cap更大的切片，再把原切片复制过去）</p>
<hr>
<h3 id="范围Range"><a href="#范围Range" class="headerlink" title="范围Range"></a>范围Range</h3><ul>
<li>用于for循环中迭代数组（array），切片（slice），通道（channel），集合（map)的元素。</li>
<li>在数组和切片中返回索引和索引对应的值，在集合中返回key-value对</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">func testRange() &#123;</span><br><span class="line">   nums := [...]int&#123;3,4,5,2&#125;</span><br><span class="line">   for _, v := range nums &#123;</span><br><span class="line">      fmt.Println(v)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   maps := map[string]string&#123;&quot;a&quot;: &quot;apple&quot;, &quot;b&quot;: &quot;banana&quot;&#125;</span><br><span class="line">   for k, v := range maps &#123;</span><br><span class="line">      fmt.Printf(&quot;key: %s value: %s\n&quot;,k ,v)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">    // 第一个是字符的索引，第二个是字符的Unicode值</span><br><span class="line">    for k, v := range &quot;abcdefg&quot; &#123;</span><br><span class="line">       fmt.Printf(&quot;%d -&gt; %d&quot;, k, v)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h3 id="Map集合"><a href="#Map集合" class="headerlink" title="Map集合"></a>Map集合</h3><ul>
<li>无序的键值对集合</li>
</ul>
<h4 id="定义Map"><a href="#定义Map" class="headerlink" title="定义Map"></a>定义Map</h4><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var map_varible map[key_data_type]value_data_type</span><br><span class="line"></span><br><span class="line">map_varible := make(map[key_data_type]value_data_type)</span><br><span class="line"></span><br><span class="line">func testMap() &#123;</span><br><span class="line">	map1 := make(map[string]string)</span><br><span class="line">	map1[&quot;a&quot;] = &quot;apple&quot;</span><br><span class="line">	for k, v := range map1 &#123;</span><br><span class="line">		fmt.Printf(&quot;%s -&gt; %s\n&quot;, k, v)</span><br><span class="line">	&#125;</span><br><span class="line">	// has 可以判断集合中是否含有这个元素</span><br><span class="line">	value, has := map1[&quot;a&quot;]</span><br><span class="line">	fmt.Println(value, has)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>delete() 函数</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">func delete(m map[Type]Type1, key Type)</span><br><span class="line"></span><br><span class="line">delete(map1, &quot;a&quot;)</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="接口"><a href="#接口" class="headerlink" title="接口"></a>接口</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">// 定义接口</span><br><span class="line">type interface_name interface &#123;</span><br><span class="line">    method_name1 [return_type]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 定义结构体</span><br><span class="line">type struct_name struct &#123;</span><br><span class="line">    title string</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 实现接口方法</span><br><span class="line">func (struct_name_varible struct_name) method_name1() [return_type] &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>实例</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import &quot;fmt&quot;</span><br><span class="line"></span><br><span class="line">type Phone interface &#123;</span><br><span class="line">	call()</span><br><span class="line">	number() string</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">type NokiaPhone struct &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">type Iphone struct &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (nokiaPhone NokiaPhone) call()  &#123;</span><br><span class="line">	fmt.Println(&quot;Nokia&quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (iphone Iphone) call()  &#123;</span><br><span class="line">	fmt.Println(&quot;iphone&quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (nokiaPhone NokiaPhone) number() string  &#123;</span><br><span class="line">	return &quot;nokia-phone-135478&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (iphone Iphone) number() string  &#123;</span><br><span class="line">	return &quot;iphone-13123&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	testInterface()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func testInterface()  &#123;</span><br><span class="line">	var phone Phone</span><br><span class="line">	phone = new(NokiaPhone)</span><br><span class="line">	phone.call()</span><br><span class="line">	fmt.Println(phone.number())</span><br><span class="line"></span><br><span class="line">	phone = new(Iphone)</span><br><span class="line">	phone.call()</span><br><span class="line">	fmt.Println(phone.number())</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<hr>
<h3 id="错误处理"><a href="#错误处理" class="headerlink" title="错误处理"></a>错误处理</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">type error interface &#123;</span><br><span class="line">    Error() string</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">func testError(a int,b int) (int, error) &#123;</span><br><span class="line">	if b == 0 &#123;</span><br><span class="line">		return 0, errors.New(&quot;除数不能为0&quot;)</span><br><span class="line">	&#125;</span><br><span class="line">	return a / b, nil</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h3 id="并发-goroutine"><a href="#并发-goroutine" class="headerlink" title="并发 goroutine"></a>并发 goroutine</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">go 函数名( 参数列表 )</span><br></pre></td></tr></table></figure>

<p><strong>通道channel</strong></p>
<blockquote>
<p>用于传递数据的一个数据结构。操作符 &lt;- 指定通道方向，发送或接收。未指定方向则是双向通道</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">func main()  &#123;</span><br><span class="line">	s := []int&#123;7, 2, 8, -9, 4, 0&#125;</span><br><span class="line">	c := make(chan int)</span><br><span class="line">	go sum(s[:len(s)/2], c)</span><br><span class="line">	go sum(s[len(s)/2:], c)</span><br><span class="line">	x, y := &lt;- c, &lt;- c</span><br><span class="line">	fmt.Println(x, y, x + y)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func sum(s []int, c chan int)  &#123;</span><br><span class="line">	sum := 0</span><br><span class="line">	for _, v := range s &#123;</span><br><span class="line">		sum += v</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	c &lt;- sum</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>通道缓冲区</strong></p>
<ul>
<li>第二个参数是缓冲区的大小</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">ch := make(chan int, 100)</span><br></pre></td></tr></table></figure>

<p><strong>遍历通道与关闭通道</strong></p>
<p>range 遍历通道时，如果通道没有关闭，会一直阻塞等到通道，这时需要主动关闭通道</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">v, ok := &lt;-ch</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">沙屿沫</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.shayvmo.cn/2022/01/16/go-basic/">http://blog.shayvmo.cn/2022/01/16/go-basic/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.shayvmo.cn" target="_blank">指尖改变世界</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Go/">Go</a></div><div class="post_share"><div class="social-share" data-image="/images/code.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/01/27/api-idempotence/"><img class="prev-cover" src= "" data-lazy-src="/images/code.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">接口幂等性设计</div></div></a></div><div class="next-post pull-right"><a href="/2022/01/16/go-import/"><img class="next-cover" src= "" data-lazy-src="/images/code.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Go语言中import导入包时：点. 、下划线_ 、别名的用法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/01/16/go-import/" title="Go语言中import导入包时：点. 、下划线_ 、别名的用法"><img class="cover" src= "" data-lazy-src="/images/code.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-16</div><div class="title">Go语言中import导入包时：点. 、下划线_ 、别名的用法</div></div></a></div><div><a href="/2022/01/16/set-goproxy/" title="go mod 设置代理 goproxy"><img class="cover" src= "" data-lazy-src="/images/code.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-16</div><div class="title">go mod 设置代理 goproxy</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/images/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">沙屿沫</div><div class="author-info__description">科技始终来源于人性</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">74</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">42</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/shayvmo"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">生活就像海洋，只有意志坚强的人才能到达彼岸。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">数据类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F"><span class="toc-number">2.</span> <span class="toc-text">变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E9%87%8F"><span class="toc-number">3.</span> <span class="toc-text">常量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#iota"><span class="toc-number">3.1.</span> <span class="toc-text">iota</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%8D%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">4.</span> <span class="toc-text">位运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="toc-number">5.</span> <span class="toc-text">条件语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5"><span class="toc-number">6.</span> <span class="toc-text">循环语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0"><span class="toc-number">7.</span> <span class="toc-text">函数</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%9A%84%E5%8F%82%E6%95%B0"><span class="toc-number">7.1.</span> <span class="toc-text">函数的参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%94%A8%E6%B3%95"><span class="toc-number">7.2.</span> <span class="toc-text">函数用法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">8.</span> <span class="toc-text">变量作用域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E7%BB%84"><span class="toc-number">9.</span> <span class="toc-text">数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8C%87%E9%92%88"><span class="toc-number">10.</span> <span class="toc-text">指针</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%93%E6%9E%84%E4%BD%93"><span class="toc-number">11.</span> <span class="toc-text">结构体</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E6%9E%84%E4%BD%93%E6%8C%87%E9%92%88"><span class="toc-number">11.1.</span> <span class="toc-text">结构体指针</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%87%E7%89%87"><span class="toc-number">12.</span> <span class="toc-text">切片</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#append-%E5%92%8C-copy"><span class="toc-number">12.1.</span> <span class="toc-text">append 和 copy</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8C%83%E5%9B%B4Range"><span class="toc-number">13.</span> <span class="toc-text">范围Range</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Map%E9%9B%86%E5%90%88"><span class="toc-number">14.</span> <span class="toc-text">Map集合</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89Map"><span class="toc-number">14.1.</span> <span class="toc-text">定义Map</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8E%A5%E5%8F%A3"><span class="toc-number">15.</span> <span class="toc-text">接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86"><span class="toc-number">16.</span> <span class="toc-text">错误处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B9%B6%E5%8F%91-goroutine"><span class="toc-number">17.</span> <span class="toc-text">并发 goroutine</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/06/05/webman-route-annotation/" title="webman 框架 注解路由插件"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="webman 框架 注解路由插件"/></a><div class="content"><a class="title" href="/2023/06/05/webman-route-annotation/" title="webman 框架 注解路由插件">webman 框架 注解路由插件</a><time datetime="2023-06-05T07:04:07.000Z" title="发表于 2023-06-05 15:04:07">2023-06-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/29/nginx-reload-not-effect/" title="windows服务器重载nginx配置无效"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="windows服务器重载nginx配置无效"/></a><div class="content"><a class="title" href="/2023/05/29/nginx-reload-not-effect/" title="windows服务器重载nginx配置无效">windows服务器重载nginx配置无效</a><time datetime="2023-05-29T08:03:45.000Z" title="发表于 2023-05-29 16:03:45">2023-05-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/24/php-aes/" title="前后端接口传输AES加密"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="前后端接口传输AES加密"/></a><div class="content"><a class="title" href="/2023/05/24/php-aes/" title="前后端接口传输AES加密">前后端接口传输AES加密</a><time datetime="2023-05-24T07:00:39.000Z" title="发表于 2023-05-24 15:00:39">2023-05-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/16/yar-demo/" title="Yar拓展，实现PHP的RPC服务"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Yar拓展，实现PHP的RPC服务"/></a><div class="content"><a class="title" href="/2022/08/16/yar-demo/" title="Yar拓展，实现PHP的RPC服务">Yar拓展，实现PHP的RPC服务</a><time datetime="2022-08-16T09:30:43.000Z" title="发表于 2022-08-16 17:30:43">2022-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/15/my-online-log/" title="线上日志系统"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="线上日志系统"/></a><div class="content"><a class="title" href="/2022/08/15/my-online-log/" title="线上日志系统">线上日志系统</a><time datetime="2022-08-15T09:03:01.000Z" title="发表于 2022-08-15 17:03:01">2022-08-15</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/images/code.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2023 By 沙屿沫</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="http://www.beian.miit.gov.cn/" target="_blank" rel="noopener"><img class="icp-icon" src= "" data-lazy-src="/images/icp.png"><span>粤ICP备18133330号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="false" async="async"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>